﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CubeController : MonoBehaviour, IEventListener
{
    public CubeData Data;

    //List<GameObject> nullGrounds = new List<GameObject>();

    [Range(0, 1)]
    public int FlipType = 0;
    //private string[] Ground = { "Trap_Ground", "Treasure_Ground","Green_Ground","Enemy_Ground","Block_Ground"};
    //public int Number;
    //private bool is_GroundFlip;
    //private Quaternion SpawnRotation;
    private Transform Spawntransform;

    //private int Stage;
    //private List<bool> TurnList = new List<bool>();

    //private List<GameObject> TurnDiceList = new List<GameObject>();

    //private List<GameObject> TurnSufaceList = new List<GameObject>();
    
    //private GameObject[] m_grounds=new GameObject[6];

    //private DiceController[] Gc = new DiceController[6];

    /// <summary>
    /// 执行翻面，应传入一个int，包含需要翻转的面的编号
    /// </summary>
    /// <param name="objs">需翻转的面的编号组成的数组</param>
    //public void FlipGrounds(int i)
    //{

    //    //foreach (int i in objs)
    //    //{
    //    //    Data.grounds[i].GetComponentInChildren<DiceController>().Flip(i, this.FlipType);
    //    //}

    //    Data.grounds[i].GetComponentInChildren<DiceController>().Flip(i, this.FlipType);
    //    //for (int i = 0; i < 6; i++) //按顺序翻面
    //    //{
    //    //    Grounds[i].GetComponentInChildren<DiceController>().Flip(i, this.FlipType);
    //    //    yield return new WaitForSeconds(2);
    //    //}
    //}

    ///// <summary>
    ///// TODO 改成传入旋转数据
    ///// </summary>
    ///// <param name="axis">int,0：y轴;1:x轴;2:z轴</param>
    ///// <param name="time">次数</param>
    //public void TurnDice(int axis, int time)
    //{
    //}


    private void Start()
    {
        //is_GroundFlip = false;
        //Number = 20;
        //Stage = 1;
        //EventNodeCore.GetInstance().AttachEventListener(EventDef.GroundSig, this);
        EventNodeCore.GetInstance().AttachEventListener(EventDef.FlipTurn, this);
        //EventNodeCore.GetInstance().AttachEventListener(EventDef._CanCubeRotate, this);
        //EventNodeCore.GetInstance().AttachEventListener(EventDef.CubeRotate, this);
        //for (int i = 0; i < 6; i++)
        //{
        //    m_grounds[i] = GetChildObject.GetChild(this.transform, i);
        //}
    }

    private void OnEnable()
    {
        Initiate();
    }
    /// <summary>
    /// 初始化方法
    /// </summary>
    public void Initiate()
    {
        //SpawnRotation = Quaternion.Euler(0, 0, 0);
        {   //Data.diceCoordinate = this.transform.position;
        //Data.grounds = this.Grounds;
        //for (int i = 0; i < 6; i++)
        //{
        //    this.Gc[i] = this.Grounds[i].GetComponentInChildren<DiceController>();
        //}
    }
        FlushCube();
        MapData.Instance.Registe(Data);
    }
    private void OnDisable()
    {
        MapData.Instance.Unregiste(Data);
    }
    private void OnDestroy()
    {
        //EventNodeCore.GetInstance().DetachEventListener(EventDef._CanCubeRotate, this);
        EventNodeCore.GetInstance().DetachEventListener(EventDef.FlipTurn, this);
    }
    /// <summary>
    /// 刷新Cube数据
    /// </summary>
    private void FlushCube()
    {
        if(Data == null)
        {
            Data = new CubeData() { Obj = gameObject};
        }
        if(transform.parent.name == "Map")
        {
            if ((Data.Index - transform.position).magnitude > 0.01)
            {
                Data.Index = new Vector3Int((int)transform.position.x, (int)transform.position.y, (int)transform.position.z);
            }
        }
        if (Data.Controller != this) Data.Controller = this;
        if(Data.Surfaces == null) Data.Surfaces = new Dictionary<Vector3, SurfaceData>();
        name = string.Concat("Cube" + Data.Index.ToString());
    }

    public int EventPriority() { return 0; }

    public bool HandleEvent(int id, object param1, object param2)
    {
        //GameObject currentDice = (GameObject)param1;
        switch (id)
        {
            case EventDef.FlipTurn:
                //StartCoroutine(TurnCube());
                break;
            //case EventDef._CanCubeRotate:
                //将所有的地面子物体信息存储在一个List列表中
                //bool is_Turn = (bool)param1;
                //TurnList.Add(is_Turn);
                //break;
        }
        return false;
    }

    /// <summary>
    /// 获取空地面
    /// </summary>
    //void GetNullGrounds()
    //{
    //    for (int i = 0; i < 6; i++)
    //    {
    //        GameObject ground = GetChildObject.GetChild(GetChildObject.GetChild(Grounds[i].transform, 0).transform, 0);
    //        if (ground.transform.childCount == 0)
    //        {
    //            nullGrounds.Add(Grounds[i]);
    //        }
    //        else if (GetChildObject.GetChild(ground.transform, 0).activeSelf == false)
    //        {
    //            nullGrounds.Add(Grounds[i]);
    //        }
    //    }
    //    Debug.Log(nullGrounds.Count);
    //}
    /// <summary>
    /// 从空的地面随机选择翻转方块并生成物体
    /// </summary>
    //void TurnDice()
    //{
    //    //如果空地大于3个
    //    if (nullGrounds.Count > 3){
    //        int turnNumber = Random.Range(4, nullGrounds.Count);
    //        RegistAction(-1);
    //    }
    //}
    private void RegistAction(int IsR)
    {
        EventNodeCore.GetInstance().HandleEvent(EventDef.Action * IsR, null, null);
    }


    //翻转后的面回收进SpareDice
    //IEnumerator ReturnDice(GameObject Dice)
    //{
    //    yield return new WaitForSeconds(1.0f);
    //    Dice.transform.parent = GameObject.Find("SpareGround").transform;
    //    ObjectPool.GetInstance().Return(Dice);
    //}

    //public void Test()
    //{
    //    StartCoroutine(GroundFlip());
    //}

    //public IEnumerator GroundFlip()
    //{
    //    //ToDo 修改翻面算法，我觉得现在这样对性能消耗太大了，尤其是之后当Cube很多的时候会在一次性进行n*6*9的遍历，之后应该改进一下这个翻转算法
    //    foreach (var cube in MapData.Instance.Cubes)
    //    {
    //        foreach (var surf in cube.Value.Surfaces)
    //        {
    //            TurnSufaceList.Add(surf.Value.Obj);
    //            foreach (var dice in surf.Value.Dices)
    //            {
    //                //不翻玩家的Suface
    //                if (dice.Value.Controller.Data.ObjectOfGround != null)
    //                {
    //                    if (dice.Value.Controller.Data.ObjectOfGround.tag == "Player")
    //                    {
    //                        TurnSufaceList.Remove(surf.Value.Obj);
    //                    }
    //                }
    //                { 
    //                //不翻玩家的Dice
    //                //TurnDiceList.Add(dice.Value.obj);
    //                //if (dice.Value.Controller.Data.ObjectOfGround != null)
    //                //{
    //                //    if (dice.Value.Controller.Data.ObjectOfGround.tag == "Player")
    //                //    {
    //                //        TurnDiceList.Remove(dice.Value.obj);
    //                //    }
    //                //}
    //            }
    //            }
    //        }
    //    }
    //    //不翻玩家的Suface
    //    for(int i = 0; i < TurnSufaceList.Count; i++)
    //    {
    //        foreach(Transform child in TurnSufaceList[i].transform)
    //        {

    //            child.GetComponent<DiceController>().Flip(0);
    //            yield return new WaitForSeconds(0.1f);
    //        }
    //    }

    //    //不翻玩家的Dice
    //    //for(int i = 0; i < TurnDiceList.Count; i++)
    //    //{
    //    //    TurnDiceList[i].GetComponent<DiceController>().Flip(0);
    //    //    yield return new WaitForSeconds(0.1f);
    //    //}
    //}
    //public IEnumerator TurnCube()
    //{
    //    if (TurnList.Contains(false))
    //    {
    //        //Debug.LogWarning("有子物体存在");
    //        yield return new WaitForEndOfFrame();
    //    }
    //    else
    //    {
    //        EventNodeCore.GetInstance().SendMessage(EventDef.CubeRotate);
    //        //没有子物体存在就进行翻面
    //        //yield return new WaitForSeconds(1f);
    //        StartCoroutine(GroundFlip());
    //    }
    //    Debug.LogWarning(TurnList.Count);
    //    TurnList.Clear();
    //    Debug.LogWarning(TurnList.Count);
    //}
    /// <summary>
    /// 判断该cube能否刷新地图，可以就返回true；
    /// </summary>
    /// <returns></returns>
    public bool CanFlip()
    {
        foreach(var item in Data.Surfaces)
        {
            if (!item.Value.Controller.CanFlip())
            {
                return false;
            }
        }
        return true;
    }
}